package com.hc.summary.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;

import kotlin.Lazy;

public abstract class LazyFragment extends Fragment {
    private View rootView;
    private boolean isViewCreated;
    private boolean isCurrentVisible;
    private boolean isDeprecated;

    private boolean isLoad;

    public LazyFragment(boolean isDeprecated){
        this.isDeprecated = isDeprecated;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if(rootView==null){
            rootView = inflater.inflate(getLayoutResId(),container,false);
        }
        if(isDeprecated){
            isViewCreated = true;
            initView(rootView);
            if(getUserVisibleHint()){
                setUserVisibleHint(true);
            }
        }else {
            initView(rootView);
        }
        return rootView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isDeprecated){
            if(isViewCreated){
                if(!isCurrentVisible && isVisibleToUser){
                    dispatchUserVisibleHint(true);
                }else if(isCurrentVisible && !isVisibleToUser){
                    dispatchUserVisibleHint(false);
                }
            }
        }
    }



    @Override
    public void onResume() {
        super.onResume();
        if(!isDeprecated){
            if(!isLoad){
                isLoad = true;
                startLazyLoad();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if(!isDeprecated){
            if(isLoad){
                stopLazyLoad();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isLoad = false;
        isCurrentVisible = false;
        isViewCreated = false;
        rootView = null;
    }

    private void dispatchUserVisibleHint(boolean visible){
        isCurrentVisible = visible;
        if(visible){
            if(!isLoad){
                isLoad = true;
                startLazyLoad();
            }
        }else {
            stopLazyLoad();
        }
    }

    public void startLazyLoad(){

    }

    public void stopLazyLoad(){

    }

    public void LazyLoadSuccess(){

    }
    public void LazyLoadFail(){
        isLoad = false;
        isCurrentVisible = false;
    }

    protected abstract void initView(View rootView);

    protected abstract int getLayoutResId();
}
